package com.example.common.util;

import com.example.common.enums.ErrorCodeEnum;
import com.example.common.exception.BusinessException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
@Component
public class JwtUtils {

    private static final long EXPIRATION_TIME = 3600_000; // 1小时
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(
            "LiuMingDengSTheBestPeopleInWorld".getBytes(StandardCharsets.UTF_8));

    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    public static Map<String, Object> parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);
            return claimsJws.getBody(); // Claims 实现了 Map 接口
        } catch (ExpiredJwtException e) {
            throw new BusinessException(ErrorCodeEnum.PERMISSION_DENIED, "Token expired");
        } catch (JwtException e) {
            throw new BusinessException(ErrorCodeEnum.PERMISSION_DENIED, "Invalid token");
        }
    }
}